package com.accp.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.accp.pojo.Goods;
import com.accp.service.GoodsService;
import com.accp.service.impl.GoodsServiceImpl;

@Controller
public class GMGoodsController {

	@Autowired
	GoodsService goodsService = new GoodsServiceImpl();

	@RequestMapping("GMgetAllGoods")
	public String getAllGoods(HttpServletRequest request) {

		List<Goods> goodsList = goodsService.selectAllGoods();

		
		for (Goods goods : goodsList) {
			System.out.println(goods.getGoodsname());
		}
		
		request.setAttribute("goodsList", goodsList);
		
		return "GMGoods";
	}

	@RequestMapping("GMgetGoodsToName")
	public String getGoodsToName(String goodsname,HttpServletRequest request) {

		
		
		System.out.println(goodsname+"!");
		List<Goods> goodsList = goodsService.selectGoodsToName(goodsname);

		
		
		
		//for (Goods goods : goodsList) {
		//	System.out.println(goods.getGoodsname());
		//}

		request.setAttribute("goodsList2", goodsList);
		
		return "GMGoods";
	}
	
	
	@RequestMapping("toUpdate")
	public String toUpdate(int goodsId,Model model){
		
		Goods goods=goodsService.selectByPrimaryKey(goodsId);
		
		
		model.addAttribute("goods", goods);
		
		
		return "GMupdateGoods";
	}
	

	@RequestMapping("updateGoods")
	public String updateGoods(int goodsid,String goodsname,double goodsprice){
		
		
		
		Goods goods=new Goods(goodsid,goodsname,goodsprice);
				
		int result=goodsService.updateByPrimaryKey(goods);
		
		if (result==1) {
			System.out.println("111");
			return  "redirect:GMgetAllGoods";
		}else{
			System.out.println("222");	
		}
		
		return null;
		//return "redirect:toUpdate?GoodsId="+goods.getGoodsid();
	}
	
	
	@RequestMapping("toDelete")
	public String toDelete(int goodsId,Model model){
		
			
		int result=0;
		try {
			result = goodsService.deleteByPrimaryKey(goodsId);
			System.out.println("删除成功");
			return "redirect:GMgetAllGoods";
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("删除失败");
			return "deleteFailed";
		}
		
		
	}
	
	@RequestMapping("toGMaddGoods")
	public String toGMaddGoods(){
		
		
		return "GMaddGoods";
	}
	
	@RequestMapping("GMaddGoods")
	public String addGoods(String goodsname,double goodsprice){
		
		Goods goods=new Goods(goodsname,goodsprice);
		
		int result=goodsService.insert(goods);
		
		if (result==1) {
			System.out.println("添加成功");
		}else{
			
			System.out.println("添加失败");
		}
		
		return "redirect:GMgetAllGoods";
	}
	
}
